﻿using QbotAGV;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WaterRobotMonitor
{
    public partial class FormZAxis : Form
    {
        public KincoAxis ZAxis { get; set; }
        public int MotorVel { get; set; }
        public int MotorDir { get; set; } = 0;
        private const int MotorVelMax = 800;
        public FormZAxis()
        {
            InitializeComponent();
            ZAxis = new KincoAxis(IPAddress.Parse("192.168.31.168"), 19003, modbus_id: 1);
        }

        private void FormZAxis_FormClosing(object sender, FormClosingEventArgs e)
        {
            Hide();
            e.Cancel = true;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                ZAxis.Begin();
                ZAxis.SetAxisMode(KincoAxis.AxisModeList.VelMode);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        private void checkEnable_CheckedChanged(object sender, EventArgs e)
        {
            ZAxis.Enable(checkEnable.Checked);
            tmMotor.Enabled = checkEnable.Checked;
        }

        private void tmMotor_Tick(object sender, EventArgs e)
        {
            RefreshMotorVel();
            ZAxis.SetVelocity(MotorVel);
        }

        private void btnMoveF_Click(object sender, EventArgs e)
        {
            MotorDir = -1;
            RefreshMotorVel();
        }

        private void RefreshMotorVel()
        {
            MotorVel = (int)(MotorVelMax / 100.0 * VxBar.Value * MotorDir);
            if (Math.Abs(MotorVel) < 100 && MotorVel != 0)
                MotorVel = 100 * Math.Sign(MotorVel);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            MotorDir = 0;
            MotorVel = 0;
            RefreshMotorVel();
        }

        private void btnMoveB_Click(object sender, EventArgs e)
        {
            MotorDir = 1;
            RefreshMotorVel();
        }
    }
}
